package simorg.actions;

import org.dom4j.Document;
import org.dom4j.Element;

import simorg.controller.AssignmentController;
import simorg.domain.Assignment;
import simorg.domain.Compound;
import simorg.domain.persistence.AssignmentTable;
import simorg.domain.persistence.CompoundTable;
import simorg.view.ModelView;
import simorg.view.Page;
import simorg.view.WebSessionContext;

public class AssignmentView extends Action {

	public static String actionName = "view";
	public AssignmentView() {
		super(actionName);
		this.controllerName = AssignmentController.controllerName;
	}
	public AssignmentView(String assignmentId) {
		super(actionName);
		this.controllerName = AssignmentController.controllerName;
		this.getRequestArgs().add(assignmentId);
	}
	
	@Override
	public ModelView checkAccess(WebSessionContext wc) throws Exception {
		return this.checkAdminAccess(wc);
	}
	
	@Override
	public ModelView process(WebSessionContext wc) throws Exception {
		ModelView mv = this.checkAdminAccess(wc);
		if ( mv != null ) return mv;
		
		Document xmlDoc = this.getBaseXml(wc);
		Element assignmentElement = xmlDoc.getRootElement().addElement( "selected-assignment" );
		int id = Integer.parseInt(this.getRequestArgs().get(0));
		Assignment assignment = AssignmentTable.findById(wc.getDbConnection(), id);
		assignment.buildDomainXml(assignmentElement, wc.getDbConnection());
		Element compoundsElement = xmlDoc.getRootElement().addElement( "compounds" );
		for (Compound c : CompoundTable.findAll(wc.getDbConnection())) {
			c.buildDomainXml(compoundsElement);
		}
		return new ModelView(Page.Assignment, xmlDoc);
	}


}
